import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { list, add, remove } from '@/services/brand';

export interface Brand {
  id: number;
  name: string;
  firstLetter: string;
  sort: number;
  productCount: number;
}

export interface BrandModelState {
  brands: Brand[];
}

export interface BrandModelType extends Model {
  namespace: 'brand';
  state: BrandModelState;
  effects: {
    query: Effect;
    add: Effect;
    remove: Effect;
  };
  reducers: {
    refresh: Reducer<BrandModelState>;
  };
}

const BrandModel: BrandModelType = {
  namespace: 'brand',
  state: {
    brands: [],
  },

  reducers: {
    refresh(state = { brands: [] }, action) {
      return {
        ...state,
        brands: action.brands,
      };
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const response = yield call(list);
      yield put({
        type: 'refresh',
        brands: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield call(add, payload);
      yield put({
        type: 'query',
      });
      callback();
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({
        type: 'query',
      });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname.startsWith('/product')) {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default BrandModel;
